package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;
    /**
     * 登入业务
     *
     * @param phone       手机号
     * @param userCode    输入的验证码
     * @param sessionCode 后端生成的验证码
     * @return user
     */
    @Override
    public User login(String phone, String userCode, String sessionCode) {
        //1.传递过来的手机号,用户输入验证码与session的验证码
        //2.校验验证码是否正确,如果不正确返回"验证码错误"
        if (!userCode.equals(sessionCode)){
            throw new BusinessException("验证码错误");
        }

        //3.根据手机号查找用户对象,判断是否为禁用,如果找到并没有禁用直接返回
        User loginUser = userMapper.findByPhone(phone);
        if (loginUser!=null){
            if (loginUser.getStatus()==1){
                throw new BusinessException("您的手机号已被禁用");
            }
        }else {
            //4.如果找不到,完善用户数据(状态为0正常),并添加用户带数据库
            loginUser=new User();
            loginUser.setStatus(0);
            loginUser.setPhone(phone);
            userMapper.save(loginUser);
        }
        //5.返回登入用户对象
        return loginUser;
    }
}
